package com.evan.kdl.test.day01;

import com.evan.kdl.util.CommonUtils;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author huangzhongliang
 * 编排2个非依赖关系的异步任务 thenCombine()
 * 我们已经知道，当其中一个Future依赖于另一个Future，使用`thenCompose()`用于组合两个Future。如果两个Future之间没有依赖关系，你希望两个Future独立运行并在两者都完成之后执行回调操作时，则使用`thenCombine()`;
 * 注意：当两个`Future`都完成时，才将两个异步任务的结果传递给`thenCombine()`的回调函数做进一步处理。
 * @time 2024/01/04 17:28
 */
public class ThenCombineDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            CommonUtils.printThreadLog("读取news文件内容");
            String context = CommonUtils.readFile("F:\\idea-workspace-personal\\juc-springboot-demo\\src\\main\\resources\\news.txt");
            return context;
        });

        CompletableFuture<String[]> future2 = CompletableFuture.supplyAsync(() -> {
            CommonUtils.printThreadLog("读取敏感词汇并解析");
            String context = CommonUtils.readFile("F:\\idea-workspace-personal\\juc-springboot-demo\\src\\main\\resources\\filter_words.txt");
            String[] words = context.split(",");
            return words;

        });
        ExecutorService executor = Executors.newFixedThreadPool(4);
        CompletableFuture<String> combinedFuture = future1.thenCombineAsync(future2, (context, words) -> {
            CommonUtils.printThreadLog("替换操作");
            for (String word : words) {
                if (context.contains(word)) {
                    //context内容有word，word被替换成**
                    context = context.replace(word, "**");
                }
            }
            return context;
        }, executor);
        String filteredContext = combinedFuture.get();
        System.out.println("filteredContext = " + filteredContext);
        executor.shutdown();
    }
}
